package pg

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/common/gensql"
	"time"
)

var _ ManagerModel = (*customManagerModel)(nil)

type (
	// ManagerModel is an interface to be customized, add more methods here,
	// and implement the added methods in customManagerModel.
	ManagerModel interface {
		managerModel
		Find(ctx context.Context, pageNo, pageSize int64) ([]*Manager, error)
		Count(ctx context.Context) (int64, error)
	}

	customManagerModel struct {
		*defaultManagerModel
		logx.Logger
		genSql *gensql.GenSql
	}
)

// NewManagerModel returns a model for the database table.
func NewManagerModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) ManagerModel {
	return &customManagerModel{
		defaultManagerModel: newManagerModel(conn, c, opts...),
		Logger:              logx.WithDuration(time.Second),
		genSql:              gensql.NewGenSql(),
	}
}

func (m *customManagerModel) Find(ctx context.Context, pageNo, pageSize int64) ([]*Manager, error) {
	query := fmt.Sprintf("select %s from %s ", managerRows, m.table)
	m.genSql.InitSql(query)
	q, v, err := m.genSql.OrderBy("create_time DESC").Limit(uint64(pageSize)).Offset(uint64((pageNo - 1) * pageSize)).ToSql()
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	var list []*Manager
	err = m.QueryRowsNoCacheCtx(ctx, &list, q, v...)
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	return list, nil
}

func (m *customManagerModel) Count(ctx context.Context) (int64, error) {
	sqlStr := fmt.Sprintf("SELECT count(uid) FROM %s", m.table)
	var count int64
	err := m.QueryRowNoCacheCtx(ctx, &count, sqlStr)
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return 0, err
	}
	return count, nil
}
